#include "hookhandler.h"
#include <QDebug>

HookHandler *HookHandler::m_instance = nullptr;

HookHandler::HookHandler(QObject *parent) : QObject(parent), mouseHook(nullptr) {}

HookHandler::~HookHandler()
{
    uninstallHook();
}

HookHandler *HookHandler::instance()
{
    if (!m_instance)
        m_instance = new HookHandler();
    return m_instance;
}

void HookHandler::installHook()
{
    if (!mouseHook) {
        mouseHook = SetWindowsHookEx(WH_MOUSE_LL, mouseProc, GetModuleHandle(nullptr), 0);
        if (!mouseHook)
            qDebug() << "Failed to install mouse hook!";
    }
}

void HookHandler::uninstallHook()
{
    if (mouseHook) {
        UnhookWindowsHookEx(mouseHook);
        mouseHook = nullptr;
    }
}

LRESULT CALLBACK HookHandler::mouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode >= 0 && (wParam == WM_MOUSEMOVE)) {
        MSLLHOOKSTRUCT *pMouse = reinterpret_cast<MSLLHOOKSTRUCT *>(lParam);
        int x = pMouse->pt.x;
        int y = pMouse->pt.y;

        emit HookHandler::instance()->mouseMoved(x, y);
    }

    return CallNextHookEx(nullptr, nCode, wParam, lParam);
}
